package com.base.service.session;

import java.sql.Timestamp;
import java.util.*;

import org.hibernate.*;
import org.hibernate.criterion.*;

import tool.JsonTool;
import tool.TimeTool;

import com.base.bean.*;




/**
 * 功能介绍：
 * 会话的基本服务类
 * trigger:
 * 是否触发业务对象
 * @author chz
 *
 */
public  class BaseSessionService {
	
	
	private SessionDaoInstance daos = SessionDaoInstance.getInstance();
	
	public static Map<Integer,SessionType> getSessionType(){
		Map<Integer,SessionType> map = new HashMap<Integer,SessionType>();
		List<SessionType> list = SessionDaoInstance.getInstance().getTypeDao().findByHql("from SessionType");
		for(SessionType st:list){
			map.put(st.getType(),st);
		}
		
		return map;
	}
	

	// criteria 接口写法
	@Deprecated
	public List<Object[]> getGroupByState2(Integer uid){
		Session session = null;
		session = daos.getMsgDao().getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		@SuppressWarnings("unchecked")
		List<Object[]> results = session.createCriteria(SessionUsrMsg.class) .setProjection( Projections.projectionList()
				.add(Property.forName("category"),"category")
		        .add( Projections.groupProperty("state"),"state" )
		        .add( Projections.rowCount(),"groupCount" )
		) .list();		
		tx.commit();
		return results;
	}
	
	// 原生查询(表名用对象的写法)
	/*  (某人)待办事项按Type分组  */
	public List getGroupByType(Integer uid){
		Session session = null;
		session = daos.getMsgDao().getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Object[]> results = session.createQuery("select count(*) ,type,category,state from SessionUsrMsg where expire > :now and state<2 and uid = :uid group by type")
								.setInteger("uid", uid).setTimestamp("now", TimeTool.getCurrentTime()).list();
		tx.commit();
		return results;
	}
	

	public List<SessionUsrMsg> getMsgList(Integer uid,Integer category,Integer offset,Integer pageSize){
		String hql = "from SessionUsrMsg a where a.created > :beforeTime and a.uid = :uid  and a.state<2 and a.category= :category order by a.created desc";
		Timestamp _time = TimeTool.nDaysLeater(-2);
		Session session = null;
		session = daos.getMsgDao().getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		Query query =  session.createQuery(hql) .setTimestamp("beforeTime", _time)
												.setInteger("uid",uid)
											 	.setInteger("category", category)
												.setFirstResult(offset)
												.setMaxResults(pageSize);
		
		List results = query.list();
		tx.commit();
		return results;
	}
	
	public List<SessionUsrMsg> getMsgList(Integer uid,Integer category,Integer maxSize){
		return this.getMsgList(uid, category, 0, maxSize);
	}
	
	/* 已办事项数量 */
	public Integer getHasdoneCount(Integer uid){
		Session session = null;
		session = daos.getMsgDao().getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		Long results = (Long) session.createQuery("select count(*)  from SessionUsrMsg where expire > :now and state=2 and uid = :uid ")
								.setInteger("uid", uid)
								.setTimestamp("now", TimeTool.getCurrentTime()).list().get(0);
		tx.commit();
		return new Integer(results.toString()); 
	}
	
	
	
	/* 获取已办实现列表 */
	public List<SessionUsrMsg> getMsgListDone(Integer uid){
		String hql = "from SessionUsrMsg where expire > :now and state=2 and uid = :uid order by created";
		Session session = null;
		session = daos.getMsgDao().getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		Query query =  session.createQuery(hql) .setTimestamp("now",TimeTool.getCurrentTime())
												.setInteger("uid", uid);
		@SuppressWarnings("unchecked")
		List results =  query.list();
		tx.commit();
		return results;
		
	}
	
	
	
	
	
	
	
	// create session
	public Integer createSession(String category,Integer creator, Integer type, Integer state,Integer trigger){
		SessionBase base =  new SessionBase(category,TimeTool.getCurrentTime(), TimeTool.nDaysLeater(2),
				creator, type, state,trigger);		
		Session session = null;
		session = daos.getBaseDao().getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		session.save(base);
		
		@SuppressWarnings("unchecked")    // 查询max cid
		List<Integer> results = session
				.createCriteria(SessionUsrMsg.class)
				.setMaxResults(1)
				.setProjection(
						Projections.projectionList().add(
								Projections.max("cid"))
				).list();
		Integer maxId = results.get(0);
		return maxId;
	}
	
	// 默认创建无触发条件的session
	public Integer createSession(String category,Integer creator, Integer type, Integer state){
		return this.createSession(category,creator, type, state,0);
	}
	
	// add msg (msg:state=0)
	public void addMsg(Integer sid, Integer uid,String title, String content, String url, Integer type,int state,int flag){
		SessionBase base = this.daos.getBaseDao().findByHql("from SessionBase a where a.sid="+sid).get(0);
		SessionUsrMsg msg =  new SessionUsrMsg(sid, uid, title, content, url, type,0,flag);
		msg.setCategory(base.getCategory());
		msg.setCreated(base.getCreated());
		msg.setExpire(base.getExpire());
		this.daos.getMsgDao().merge(msg);
	}
	
	// finish msg (msg:state=1)
	public void doneMsg(Integer msgId){
		SessionUsrMsg msg =  this.daos.getMsgDao().findByHql("from SessionUsrMsg where id="+msgId).get(0);
		msg.setState(1);
		this.daos.getMsgDao().merge(msg);
	}
	
	// save reply 
	public void addReply(Integer msgId,Integer oppType, String reply, Integer type,Integer state) {
		SessionUsrMsg msg = this.daos.getMsgDao().findByHql("from SessionUsrMsg a where a.id="+msgId).get(0);
		SessionUsrReply usrReply = new SessionUsrReply (msgId, oppType, reply, type,state);
		usrReply.setSid(msg.getSid());
		usrReply.setUid(msg.getUid());
		usrReply.setMsgId(msgId);
		usrReply.setCreated(TimeTool.getCurrentTime());	
		this.daos.getReplyDao().merge(usrReply);
	}
	
	public List<SessionUsrReply> getReplyList(Integer sid){
		return this.daos.getReplyDao().findByHql("from SessionUsrReply where sid="+sid);
	}
	
	
	public void createEntity(Integer sid, String objName, Integer objId,Object obj, Integer type, Integer state){
		SessionObj sobj = new SessionObj(sid,objName, objId,JsonTool.obj2json(obj), type, state);
		this.daos.getObjDao().merge(sobj);	
	}
	
	public void updateEntity(Integer sid,Object obj){
		SessionObj sobj = this.daos.getObjDao().findByHql("from SessionObj a where a.sid="+sid).get(0);
		sobj.setObjJson(JsonTool.obj2json(obj));
		this.daos.getObjDao().merge(sobj);
	}
	
	
	public String getObj(Integer sid,String objName){
		SessionObj obj = this.daos.getObjDao().findByHql("from SessionObj a where a.sid="+sid +" and a.objName='"+objName+"'").get(0);
		return obj.getObjJson();
		
	}

	public SessionDaoInstance getDaos() {
		return daos;
	}

	public void setDaos(SessionDaoInstance daos) {
		this.daos = daos;
	}
	


	

	

	

}
